package cn.tianjindong.blog.common.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Cookie相关操作工具类
 * 
 * @author 田 金 东
 *
 */
public class CookieUtils {

	/**
	 * 根据Cookie的名字获取cookie
	 * 
	 * @param request
	 * @param name
	 * @return
	 */
	public static Cookie getCookie(HttpServletRequest request, String name) {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(name)) {
					return cookie;
				}
			}
		}
		return null;
	}

	public static String getCookieValue(HttpServletRequest request, String name) {
		Cookie cookie = getCookie(request, name);
		if (cookie != null) {
			return cookie.getValue();
		}
		return null;
	}

	/**
	 * 添加Cookie，并将携带路径设置为项目根路径
	 * 
	 * @param response
	 * @param name
	 * @param value
	 */
	public static void setRootPathCookie(HttpServletRequest request, HttpServletResponse response, String name,
			String value) {
		setCookie(request, response, name, value, "/" + request.getContextPath());
	}

	/**
	 * 添加Cookie，并设置指定的携带路径
	 * 
	 * @param response
	 * @param name
	 * @param value
	 */
	public static void setCookie(HttpServletRequest request, HttpServletResponse response, String name, String value,
			String path) {
		Cookie cookie = new Cookie(name, value);
		cookie.setPath(path);
		response.addCookie(cookie);
	}

	/**
	 * 删除指定的cookie
	 * 
	 * @param request
	 * @param response
	 * @param name
	 */
	public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, String name) {
		Cookie cookie = getCookie(request, name);
		if (cookie != null) {
			cookie.setMaxAge(0);
			response.addCookie(cookie);
		}
	}
}
